package collecttion;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

//增强型for循环
public class NewForDemo {
    public static void main(String[] args) {
        String[] array = {"one","two","three","four","five"};
        for (int i=0;i<array.length;i++){
            String str = array[i];
            System.out.println(str);
        }
        System.out.println("--------------");
        //接受每个元素的变量 :  集合名称
        for (String str : array){
            System.out.println(str);
        }
        System.out.println("--------------");
        Collection<String> c = new ArrayList<>();
        c.add("one");  //add(E e) ==> add(String e)
        c.add("two");
        c.add("three");
        c.add("four");
        c.add("five");
        //c.add(123);  //编译不通过，实参类型违背了当前集合指定的泛型E的实际类型String
        Iterator it = c.iterator();
        while (it.hasNext()){
            String str = (String)it.next();
            System.out.println(str);
        }

        Iterator<String> it1 = c.iterator();//迭代器指定的泛型应当与其遍历的集合泛型一致(泛型原型Object)
        while (it.hasNext()){
            String str = it1.next();//指定泛型后,获取元素无需再手动造型
            System.out.println(str);
        }

        System.out.println("--------------");
        for (Object obj : c){
            String str = (String)obj;
            System.out.println(str);
        }
        System.out.println("--------------");
        for (String str : c){
            System.out.println(str);
        }
    }
}
